/* global Highcharts, d3, undersore, _, require, define */
/* jshint -W119 */

import {store} from "@/components/chart/common/store";
import * as echarts from "echarts";

const buildChart = function (svgSelector, data, columnFields, rowFields, options) {
  //一级维度
  const dimensionField = columnFields.concat(rowFields).find(function (d) {
    return d.slaveType === 0;
  });
  //度量
  const measureField = rowFields.concat(columnFields).find(function (d) {
    return d.slaveType === 1;
  });
  if (!dimensionField || !measureField) {
    return false;
  }
  let config = options.chartConfig;
  if (!config) {
    config = {}
  }

  const option = {
    color: config.MultiColors,
    toolbox: {
      feature: {
        dataView: {readOnly: false},
        restore: {},
        saveAsImage: {}
      }
    },
    legend: {},
    series: [],
    others: {
      dimensionField: dimensionField,
      measureField: measureField,
      categories: {},
      data: data,
      labelFormater: config.labelFormater || "<%=name%>: <%=ratio%>",
      datamarking: options.dataMarking
    }
  };

  const series = {
    type: 'funnel',
    label: {},
    data: [],
    left: 0.05
  }

  const subdimensionField = options.colorMark ? options.colorMark.annexField : null;
  if (subdimensionField) {
    const group = _.uniqBy(data.map(d => {
      return {
        value: d[subdimensionField.name]
      }
    }),'value')
    series.width = 1.0 * 1 / group.length
    series.left += series.width
    group.forEach(item1 => {
      series.data = data.filter(item => item1.value == item[subdimensionField.name]).map(function (d) {
        return {
          value: d[measureField.name],
          name: d[dimensionField.name]
        };
      })
      series.name = item1.value
      series.width = series.width * 100 +'%'
      series.left = series.left * 100 +'%'
      option.series.push(Object.assign({},series));
    })
  }else{
    series.name = measureField.name,
    series.data = data.map(function (d) {
      return {
        value: d[measureField.name],
        name: d[dimensionField.name]
      };
    });
    option.series.push(Object.assign({},series));
  }

  var dom_container = $(svgSelector).children('#chart')[0];
  var chartInstance = new chart(dom_container, option);
  return chartInstance;
};

const chart = function (dom_container, opt) {
  var _calldata;
  var _mData = opt.series[0].data;
  var datamarkingopt = opt.others.datamarking;
  var datamarkingmapping = {}
  delete opt.others.data;
  delete opt.others.datamarking;
  //处理数据脱敏
  if (datamarkingopt) {
    datamarkingopt.dimensions.forEach(function (dko) {
      if (dko.DataMarkingEnable) {
        datamarkingmapping[dko.name] = true;
      }
    });
  }
  const self = this;
  const myChart = echarts.init(dom_container, store.darkMode ? 'dark' : '', {
    renderer: store.renderer,
    useDirtyRect: store.useDirtyRect
  });

  let chart_opt = {
    tooltip: {
      formatter: function (args) {
        return opt.others.dimensionField.name + ":" + args.name + "<br/>" + opt.others.measureField.name + ":" + Number(args.value).toMeasureFormart(opt.others.measureField.numberFormat) + "<br/>占比:" + args.percent + "%";
      }
    },
    legend: {
      top: '5%',
      left: 'center',
      formatter: function (name) {
        var result = name;
        if (datamarkingopt && datamarkingmapping[opt.others.dimensionField.name]) {
          result = result.marking();
        }
        return result;
      }
    }
  };

  const labelFormatter = function (args) {
    var name = args.name;
    if (datamarkingopt && datamarkingmapping[opt.others.dimensionField.name]) {
      name = name.marking();
    }
    return opt.others.labelFormater.replace(/\<|\%|\=|\>/g, "").replace("name", name).replace("value", args.value.toMeasureFormart(chart_opt.others.measureField.numberFormat)).replace("ratio", args.percent + "%");
  };

  const setOption = function (opt, ext) {
    if (ext) {
      chart_opt = $.extend(true, chart_opt, opt);
    } else {
      chart_opt = opt;
    }
    chart_opt.series[0].label.formatter = labelFormatter;
    myChart.setOption(chart_opt);
  };

  if (opt) {
    setOption(opt, true);
    chart_opt.series.forEach(function (d) {
      d.label.formatter = labelFormatter;
    });
  }

  this.setOption = setOption;
  this.removeChart = function () {
      myChart.dispose();
    $(dom_container).unbind("contextmenu");
  }
  this.update = function (data) {
    _mData = data;
    chart_opt.series[0].data = data.map(function (d) {
      return {
        value: d[chart_opt.others.measureField.name],
        name: d[chart_opt.others.dimensionField.name]
      };
    });
    //提取一级维度
    var categories = Enumerable.from(data).select(function (d) {
      return d[chart_opt.others.dimensionField.name];
    }).toArray();
    //提取一级维度
    categories = _.unionBy(data, function (d) {
      return d[chart_opt.others.dimensionField.name];
    })
    chart_opt.legend.data = categories;
    chart_opt.others.categories = categories;
    setOption(chart_opt, true);
  }
  this.resize = myChart.resize
};

export const PyramidChart = {
  build: buildChart
};

